const Service = require('egg').Service;
const moment = require('moment');
const fs = require('fs');
const crypto = require('crypto');
// service中不知道怎样直接调用helper
const helper = require('../extend/helper.js');

class FuyouSplitAccountService extends Service {
	
	// 电商分账企业户开户
	async allocationCompany(customInfo){
		
		const {
			ctx
		} = this;
		
		// 获取post参数
		const requestObj = ctx.request.body;

		var reqJson = requestObj;
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "FZ" + Math.ceil(Math.random()*100);
		
		// 签名字段和顺序
		const constSignArray = ['artifNm', 'bankLicense', 'mchntCd', 'mchntTxnSsn', 'bankNm', 'brandName', 'capacntno', 
								 'certifId', 'cityId', 'taxNum', 'licenseIndate', 'custNm', 'ver'];
							
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		if (reqJson.signature === false){
			return '系统错误：签名缺少参数！';
		}

		var certificateFile = './merchantMaterial/'+customInfo.pcCode+'/certificate.jpg';

		if(!fs.existsSync(certificateFile)) {
			return '三证图片不存在';
		}
		var identityFile = './merchantMaterial/'+customInfo.pcCode+'/identity.jpg';
		if(!fs.existsSync(identityFile)) {
			return '身份证图片不存在';
		}
		
		var reqUrl = this.app.config.fuyou.splitAccount.reqHost + this.app.config.fuyou.splitAccount.createCompanyUrl;
		// 记录请求日志,不记录图片，否则内容超长，意义也不大
		const logId = await ctx.service.common.addReqLog('FY_allocationCompany', reqUrl, reqJson);
		
		let certificateImg = fs.readFileSync(certificateFile);
		reqJson.accessory1 = Buffer.from(certificateImg, 'binary').toString('base64');
		let identityImg = fs.readFileSync(identityFile);
		reqJson.accessory2 = Buffer.from(identityImg, 'binary').toString('base64');

		const result = await this.app.curl(reqUrl, {
			method: 'POST',
			headers: {
				'content-type': 'application/json',
			},
			data: reqJson,
			timeout: 9000,
			// 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
//    		dataType: 'json',
		});
		// 记录返回日志
		ctx.service.common.setReqLog(logId, JSON.stringify(result));
		if (result.status != 200){
			return result.res.statusMessage;
		}else{
			result.data = JSON.parse(result.data);
			ctx.service.common.setReqLog(logId, JSON.stringify(result));
		}
		
		var returnData = result.data.obj;

		if (returnData.respCode != '0000' && returnData.respCode !== 0){
			return '系统错误：' + returnData.respDesc;
		}

		return returnData;
	}
	
	// 分账导入
	async splitRuleCreate(customInfo){
		
		const {
			ctx
		} = this;
		
		// 获取post参数
		const requestObj = ctx.request.body;
		
		var reqJson = {};
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "GZ" + Math.ceil(Math.random()*100);
		reqJson.mchntName = customInfo.pcName;
		reqJson.splitCause = '业务往来';
		reqJson.autoSplit = 0;
//		reqJson.splitStartTime = '2019-10-31'; // 自动分账开始日期
		reqJson.subType = 0; // 分账类型
		reqJson.splitInfo = [{
			splitScale: 0,  // 分账比例百分比
			isRange: 1,     // 区间值
			splitAmt: 0,    // 固定值
			splitRangeAmt: "1-99999999",
			splitAccount: customInfo.pcPayConfig.fuyou.splitLoginId,  // 企业户 loginID或商户号
			contractSsn: customInfo.pcPayConfig.fuyou.contractSsn,  // 平台与参与方合同编号
			contractName: '润雄科技与' + customInfo.pcShotName + '电商分账合同',  // 平台与参与方合同名称
			participant: '润雄科技|' + customInfo.pcShotName, // 合同参与方
			startDate: customInfo.pcPayConfig.fuyou.contractStartDate, // 合同开始日期
			endDate: customInfo.pcPayConfig.fuyou.contractEndDate, // 合同结束日期
			accessory1: '', // 商户与分账参与方合同
//			accessory2: '', // 富友分账合同 详见对接材料包附件二《分账明细协议》
		}];
		
		// 判断是否有父级分账
		var parentCustom = false;
		if (customInfo.pcParentId != 0){
			parentCustom = await this.app.mysql.get('pay_customer', {pcId: customInfo.pcParentId});
			reqJson.splitInfo.push({
				splitScale: 0,  // 分账比例百分比
				isRange: 1,     // 区间值
				splitAmt: 0,    // 固定值
				splitRangeAmt: "1-99999999",
				splitAccount: parentCustom.pcPayConfig.fuyou.splitLoginId,  // 企业户 loginID或商户号
				contractSsn: parentCustom.pcPayConfig.fuyou.contractSsn,  // 平台与参与方合同编号
				contractName: '润雄科技与' + parentCustom.pcShotName + '电商分账合同',  // 平台与参与方合同名称
				participant: '润雄科技|' + parentCustom.pcShotName, // 合同参与方
				startDate: parentCustom.contractStartDate, // 合同开始日期
				endDate: parentCustom.contractEndDate, // 合同结束日期
				accessory1: '', // 商户与分账参与方合同
	//			accessory2: '', // 富友分账合同 详见对接材料包附件二《分账明细协议》
			});
		}
		
		console.log('reqJson：');
		console.log(reqJson);
		// 签名字段和顺序
		const constSignArray = ['mchntCd', 'autoSplit'];
							
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		if (reqJson.signature === false){
			return '系统错误：签名缺少参数！';
		}
		
		var reqUrl = this.app.config.fuyou.splitAccount.reqHost + this.app.config.fuyou.splitAccount.splitRuleCreate;
		
		// 记录请求日志,不记录图片，否则内容超长，意义也不大
		const logId = await ctx.service.common.addReqLog('FY_splitRuleCreate', reqUrl, reqJson);
		
		// 添加合同图片 ////////////////////////////////////////////////////////////////////////////////////
		var contractFile = './merchantMaterial/'+customInfo.pcCode+'/contract.jpg';
		if(!fs.existsSync(contractFile)) {
			return '合同图片不存在';
		}
		let certificateImg = fs.readFileSync(contractFile);
		reqJson.splitInfo[0].accessory1 = Buffer.from(certificateImg, 'binary').toString('base64');
		
		// 添加父级合同图片
		if (parentCustom){
			var parentContractFile = './merchantMaterial/'+parentCustom.pcCode+'/contract.jpg';
			if(!fs.existsSync(parentContractFile)) {
				return '父级合同图片不存在';
			}
			let parentCertificateImg = fs.readFileSync(parentContractFile);
			reqJson.splitInfo[1].accessory1 = Buffer.from(parentCertificateImg, 'binary').toString('base64');
		}
		// 添加合同图片 ////////////////////////////////////////////////////////////////////////////////////
		
		const result = await this.app.curl(reqUrl, {
			method: 'POST',
			headers: {
				'content-type': 'application/json',
			},
			data: reqJson,
			timeout: 9000,
			// 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
//    		dataType: 'json',
		});
		console.log('req result:');
		console.log(result);
		// 记录返回日志
		ctx.service.common.setReqLog(logId, JSON.stringify(result));
		
		if (result.status != 200){
			return result.res.statusMessage;
		}else{
			console.log('return json data:');
			console.log(JSON.parse(result.data));
			result.data = JSON.parse(result.data);
			ctx.service.common.setReqLog(logId, JSON.stringify(result));
		}
		
		var returnData
		if (result.data.obj){
			var returnData = result.data.obj;
		}else{
			var returnData = result.data;
		}

		if (returnData.respCode != '0000' && returnData.respCode !== 0){
			return '系统错误：' + returnData.respDesc;
		}

		return returnData;
	}

	// 订单分账
	async orderSplit(customInfo, orderInfo){
		
		const {
			ctx
		} = this;
		
		console.log('分账金额带小数：');
		console.log(orderInfo.poPrice * (1 - customInfo.pcRate));
		var osMoney = parseInt(orderInfo.poPrice * (1 - customInfo.pcRate));
		if (orderInfo.poPrice === 1){
			osMoney = 1;
		}

		// 判断是否有父级分账
		var parentCustom = false;
		var parentMoney = 0;
		if (customInfo.pcParentId != 0){
			parentCustom = await this.app.mysql.get('pay_customer', {pcId: customInfo.pcParentId});
			parentMoney =  parseInt(orderInfo.poPrice * (parentCustom.pcRate - customInfo.pcRate));
		}
		
		// 获取post参数
		const requestObj = ctx.request.body;
		
		var reqJson = {};
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "DD" + Math.ceil(Math.random()*100);
		reqJson.splitSsn = customInfo.pcPayConfig.fuyou.splitSsn; // 分账导入时，富友生成的分账编号
		reqJson.mchntTxnNum = orderInfo.poServerOrderId; // 对应原交易的请求流水号:订单号
		reqJson.amt = orderInfo.poPrice; // 分账金额
		reqJson.splitInfo = [{
			splitAmt: osMoney, // 
			splitAccount: customInfo.pcPayConfig.fuyou.splitLoginId,  // 企业户 loginID 和商户号
		}];
		if (parentCustom){
			reqJson.splitInfo.push({
				splitAmt: parentMoney, // 
				splitAccount: parentCustom.pcPayConfig.fuyou.splitLoginId,  // 企业户 loginID 和商户号
			});
		}
		
		console.log('分账reqJson：');
		console.log(reqJson);
//		return '测试发送内容';
		// 签名字段和顺序
		const constSignArray = ['mchntCd', 'splitSsn', 'mchntTxnNum'];
							
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		if (reqJson.signature === false){
			return '系统错误：签名缺少参数！';
		}
		
		var reqUrl = this.app.config.fuyou.splitAccount.reqHost + this.app.config.fuyou.splitAccount.orderSplit;
		
		const reqReturn = await this.postReq(reqUrl ,reqJson, 'FY_orderSplit');
		if (typeof(reqReturn) == 'object'){
			// 记录日志
			var pslParentId = null;
			var pslParentMoney = null;
			var pslParentRate = null;
			if (parentCustom){
				pslParentId = parentCustom.pslParentId;
				pslParentMoney = parentCustom.pslParentMoney;
				pslParentRate = parentCustom.pslParentRate;
			}
			var createUser = 'system';
			ctx.service.splitLog.add(customInfo.pcId, 'fy', orderInfo.poServerId, reqJson.mchntTxnSsn, orderInfo.poPrice, reqReturn, 
				customInfo.pcId, osMoney, customInfo.pcRate, pslParentId, pslParentMoney, 
				pslParentRate, createUser);
			return true;
		} else {
			return reqReturn;
		}
	}
	
	// 订单分账撤销
	async orderSplitCancel(mchntTxnNum){
		
		const {
			ctx
		} = this;
		
		var reqJson = {};
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "QX" + Math.ceil(Math.random()*100);
		reqJson.splitNum = 'dd'; // 原分账订单号
		reqJson.mchntTxnNum = '1432FY20191104105140XD9146'; // 对应原交易的请求流水号:订单号
		reqJson.revokeAmt = 1; // 需撤销金额
		reqJson.splitAccount = '19920002716'; // 企业户 loginID 和商户号
		reqJson.payType = '04'; // 01:余额支付 04：微信支付  05：支付宝支付
		
		console.log('取消分账reqJson：');
		console.log(reqJson);
		
		// 签名字段和顺序
		const constSignArray = ['splitNum', 'mchntTxnNum', 'revokeAmt', 'splitAccount', 'payType', 'mchntCd', 'mchntTxnSsn'];
							
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		if (reqJson.signature === false){
			return '系统错误：签名缺少参数！';
		}
		
		var reqUrl = this.app.config.fuyou.splitAccount.reqHost + this.app.config.fuyou.splitAccount.orderSplitCancel;
		
		const reqReturn = await this.postReq(reqUrl ,reqJson, 'FY_orderSplitCancel');
		if (typeof(reqReturn) == 'object'){
			return true;
		} else {
			return reqReturn;
		}
	}
	
	// 微信参数配置
	async setWxConfig(customInfo){
		
		const {
			ctx
		} = this;
		
		// 获取post参数
		const requestObj = ctx.request.body;
		
		var reqJson = {};
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "WX" + Math.ceil(Math.random()*100);
		reqJson.loginId = customInfo.pcPayConfig.fuyou.splitLoginId;
		reqJson.configs = [{
			jsapiPath: 'https://emedia.sbedian.com/api/pay/',
			subAppid: 'wxb8f879f3ecc43dc5',
			subscribeAppid: 'wxb8f879f3ecc43dc5',
		}];
		var jsapiPath = '';
		var subAppid = '';
		var subscribeAppid = '';
		for(var i in reqJson.configs){
			jsapiPath = jsapiPath + reqJson.configs[i].jsapiPath;
			subAppid = subAppid + reqJson.configs[i].subAppid;
			subscribeAppid = subscribeAppid + reqJson.configs[i].subscribeAppid;
		}
		reqJson.jsapiPath = jsapiPath;
		reqJson.subAppid = subAppid;
		reqJson.subscribeAppid = subscribeAppid;
		
		console.log('reqJson:');
		console.log(reqJson);
		
		// 签名字段和顺序
		const constSignArray = ['ver', 'mchntCd', 'loginId', 'mchntTxnSsn', 'jsapiPath', 'subAppid', 'subscribeAppid'];
		
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		
		var reqUrl = this.app.config.fuyou.splitAccount.reqHost + this.app.config.fuyou.splitAccount.setWxConfig;
		
		const reqReturn = await this.postReq(reqUrl ,reqJson, 'FY_setWxConfig');
		if (typeof(reqReturn) == 'object'){
			return true;
		} else {
			return reqReturn;
		}
	}
	
	// 微信支付
	async wxPay(customInfo){
		
		const {
			ctx
		} = this;
		
		// 获取post参数
		const requestObj = ctx.request.body;
		
		var reqJson = {};
		reqJson.ver = this.app.config.fuyou.splitAccount.ver;
		reqJson.mchntCd = this.app.config.fuyou.splitAccount.mchntCd;
		reqJson.mchntTxnSsn = "M" + moment().utc().utcOffset(8).format("YYYYMMDDHHmmss") + "XD" + Math.ceil(Math.random()*100);
		reqJson.paymentType = '04';
		reqJson.channel = '03'; // 01-PC 02-H5 03-微信公众号 05-微信小程序
		reqJson.intoAccount = '';
		reqJson.amt = '';
		reqJson.splitSsn = customInfo.pcPayConfig.fuyou.splitSsn;
		reqJson.splitType = 0 ; // 直接分账
		reqJson.purpose = '07'; // 文化娱乐
		reqJson.goodsType = '74'; // 生活娱乐充值
		reqJson.subject = ''; // 商户的标题/名称/订单的标题
		reqJson.goodsDes = '';
		reqJson.termIp = '';
		reqJson.reserveddeviceInfo = '';
		reqJson.notifyUrl = ctx.request.origin + '/tkPayCallback/fyds';
		reqJson.orderType = ''; // GZXS--公众号线上、  LPXS--小程序线上
		reqJson.openid = '';
		reqJson.subOpenid = '';
		reqJson.subAppid = ''; // APP 时必传  （openid 不传，这个是备用字段；subopenid 对应公众号支付的用户标识 openid，支付宝 userid；subappid 对应公众号 appid，服务窗模式这个不填。 ）

		// 签名字段和顺序
		const constSignArray = ['intoAccount', 'mchntTxnSsn', 'mchntCd', 'paymentType', 'termIp', 'amt'];
		
		reqJson.signature = await this.createSign(reqJson, constSignArray);
		
		const reqReturn = await this.postReq(reqUrl ,reqJson, 'FY_orderSplitCancel');
		
		return reqReturn;
		if (typeof(reqReturn) == 'object'){
			return true;
		} else {
			return reqReturn;
		}
	}

	// 创建签名
	async createSign(reqJson, constSignArray) {
		
		var signStr = '';
		for(var param in constSignArray) {
			console.log('param:' + constSignArray[param]);
			if (reqJson[constSignArray[param]] == undefined){
				return false;
			}

		    signStr += '|' + reqJson[constSignArray[param]];
		}
		signStr = signStr.substr(1);
        
        var sign = await this.getSign(signStr);
        return sign;
	}
	
	// 签名字符串
	async getSign(signStr){
		console.log('签名字符串：')
		console.log(signStr)
		
		//获取密匙和公钥
		let privateKey = this.app.config.fuyou.splitAccount.rsaKey.privateKey;
		
		privateKey = helper.formatPKCKey(privateKey, true, false); //转成需要的pem格式。

		const verify = crypto.createSign('sha1WithRSAEncryption'); //处理签名
		console.log('privateKey:' + privateKey);
		verify.update(signStr);
//		verify.end();
		const signature = verify.sign(privateKey, 'base64');

		console.log('signature:');
		console.log(signature);

		return signature;
	}
	
	// 分账请求
	async postReq(reqUrl ,reqJson, reqName){
		
		const {
			ctx
		} = this;
		
		// 记录请求日志
		const logId = await ctx.service.common.addReqLog(reqName, reqUrl, reqJson);
		console.log('req url:');
		console.log(reqUrl);
		const result = await this.app.curl(reqUrl, {
			method: 'POST',
			headers: {
				'content-type': 'application/json',
			},
			data: reqJson,
			// 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
//    		dataType: 'json',
			timeout: [ 1000, 30000],
		});
		console.log('req result:');
		console.log(result);
		// 记录返回日志
		await ctx.service.common.setReqLog(logId, JSON.stringify(result));
		
		if (result.status != 200){
			return result.res.statusMessage;
		}else{
			result.data = JSON.parse(result.data);
			ctx.service.common.setReqLog(logId, JSON.stringify(result));
		}
		
		var returnData
		if (result.data.obj){
			var returnData = result.data.obj;
		}else{
			var returnData = result.data;
		}

		if (returnData.respCode != '0000' && returnData.respCode !== 0){
			return '系统错误：' + returnData.respDesc;
		}
		
		return returnData;
	}
}

module.exports = FuyouSplitAccountService;
;